package com.yonyou.brigade.cron.user.didi;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.didi.model.DiDiUser;
import com.yonyou.brigade.third_parties.didi.service.IDiDiUserService;
import com.yonyou.brigade.third_parties.didi.util.DiDiUtil;
import com.yonyou.brigade.util.mail.MailSenderUtil;
import com.yonyou.ybzboot.starter.elasticjob.lite.annotation.ElasticJobConfig;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 滴滴用户同步
 *
 * @author kangfw5
 * @since 2019-07-13
 */
@Slf4j
@ElasticJobConfig(cron = "0 20 5 * * ?", shardingTotalCount = 1)
public class SyncDidiUserJob implements SimpleJob {
    @Autowired
    private IBriChannelService briChannelService;
    @Autowired
    private IUserCenterService userCenterService;
    @Autowired
    private IDiDiUserService didiUserService;
    @Autowired
    private IDeveloperService developerService;

    @Override
    public void execute(ShardingContext shardingContext) {
        List<BriChannel> channelList = briChannelService.getEnableChannelByChannel(ChannelEnum.DIDI.getName());
        for (BriChannel channel : channelList) {
            try {
                if (channel != null && BriChannel.SYNCUSER == channel.getSyncUser()) {
                    String tenant = channel.getTenant();
                    StringBuilder sb = new StringBuilder("滴滴用户同步，租户：").append(tenant).append("\r\n");
                    log.info("滴滴人员更新任务开始，租户{}", tenant);

                    List<UcUserDto> userList = userCenterService.getUcUsersByTenantId(tenant);
                    if (CollectionUtils.isEmpty(userList)) {
                        continue;
                    }
                    Wrapper<DiDiUser> wrapper = new EntityWrapper<>();
                    wrapper.eq(DiDiUser.TENANT, tenant);
                    List<DiDiUser> didiUserList = didiUserService.selectList(wrapper);

                    Map<String, UcUserDto> ucUserDtoMap = new HashMap<>();
                    List<DiDiUser> invalidUserList = new ArrayList<>();

                    userList.forEach(ucUserDto -> ucUserDtoMap.put(ucUserDto.getPhone(), ucUserDto));
                    //循环商旅服务本地已经缓存的用户
                    didiUserList.forEach(didiUser -> {
                        UcUserDto ucUser = ucUserDtoMap.get(didiUser.getPhone());
                        if (ucUser == null || ucUser.getDr() == 1 || ucUser.getValid() == 0) {
                            invalidUserList.add(didiUser);
                        }
                        ucUserDtoMap.remove(didiUser.getPhone());
                    });
                    //循环其他用户
                    sb.append("新增用户：").append("\r\n");
                    for (String phone : ucUserDtoMap.keySet()) {
                        UcUserDto ucUserDto = ucUserDtoMap.get(phone);
                        if (ucUserDto.getValid() == 0 || ucUserDto.getDr() == 1) {
                            invalidUserList.add(DiDiUtil.convertToDiDiUser(tenant, ucUserDto));
                        } else {
                            DiDiUser didiUser = DiDiUtil.convertToDiDiUser(tenant, ucUserDto);
                            try {
                                didiUserService.addSingleUser(tenant, didiUser);
                            } catch (Exception e) {
                                sb.append(phone).append(e.getMessage()).append("\r\n");
                            }
                        }
                    }
                    log.info("滴滴人员更新任务，删除用户，租户{}", tenant);
                    try {
                        didiUserService.deleteUsers(tenant, invalidUserList);
                    } catch (Exception e) {
                        sb.append("删除用户：").append("\r\n");
                        sb.append(e.getMessage()).append("\r\n");
                    }
                    MailSenderUtil.sendCommonMail(developerService.listEmailByType("YY"), "滴滴用户定时更新", sb.toString());
                    log.info("滴滴人员更新任务结束，租户{}", tenant);
                } else {
                    log.info("该租户" + channel.getTenant() + "未配置同步用户");
                }
            } catch (Exception e) {
                String msg = "滴滴更新异常，租户：" + channel.getTenant() + "异常信息：" + e.getMessage();
                MailSenderUtil.sendCommonMail(developerService.listEmailByType("KF"), "滴滴人员更新异常结束", msg);
            }
        }
    }
}
